<template>
  <el-dialog title="规则参数维护" width="60%" draggable :close-on-click-modal="false" v-model="visible" @open="submitted = false">
    <el-tabs tab-position="left" style="height: 400px">
      <!-- 遍历属性，每个分组对应一个表单，每个属性对应一个表单项 -->
      <el-tab-pane :label="group.name" v-for="(group, gidx) in dataForm.attrgroups" :key="group.id">
      <el-scrollbar>
        <el-form label-width="180px">
          <el-form-item :label="attr.name" v-for="(attr, aidx) in group.attrs" :key="attr.id">
            <el-col :span="10">
              <el-input v-model="dataForm.baseAttrs[gidx][aidx].id" type="hidden" v-show="false"></el-input>
              <el-select v-model="dataForm.baseAttrs[gidx][aidx].options" :multiple="attr.multiple === 1" style="width: 100%" filterable allow-create default-first-option placeholder="请选择或输入值">
                <el-option v-for="(val, vidx) in attr.options.split(';')" :key="vidx" :label="val" :value="val"></el-option>
              </el-select>
            </el-col>
            <el-col :span="4" style="text-align: center">
              <el-checkbox v-model="dataForm.baseAttrs[gidx][aidx].visible" :true-label="1" :false-label="0">快速展示</el-checkbox>
            </el-col>
          </el-form-item>
        </el-form>
      </el-scrollbar>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <div class="ad-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()" :disabled="submitted">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import http from "@/utils/httpRequest";
import { ElMessage } from "element-plus";
import { ref, reactive, defineExpose, defineEmits } from "vue";

// 表单数据
const dataForm = reactive({
  id: undefined,
  // SPU 属性值
  baseAttrs: [],
  // 分类下所有属性分组和属性值数据
  attrgroups: [],
});

// 弹窗是否显示
const visible = ref(false);

// 提交按钮是否禁用
const submitted = ref(false);

// 父级组件的自定义事件
const emit = defineEmits(['loadTableData']);

// 初始化数据
const initForm = (d) => {
  dataForm.id = d.id;
  visible.value = true;
  http
    .post({
      url: `/product/spu/attr-attrgroup-list?spuId=${d.id}&categoryId=${d.categoryId}`,
    })
    .then(({ data }) => {
      if (http.success(data)) {
        let form = data.body;
        // 分类下所有属性分组和属性值数据
        dataForm.attrgroups = form.attrgroups;
        // SPU属性值
        let selectAttrs = form.baseAttrs;
        let selectAttrsObj = {};
        for (let i = 0; i < selectAttrs.length; i++) {
          let attr = selectAttrs[i];
          selectAttrsObj[attr.id] = attr;
        }
        form.attrgroups.forEach((item) => {
          let attrArray = [];
          item.attrs.forEach((attr) => {
            if (selectAttrsObj.hasOwnProperty(attr.id)) {
              attrArray.push(selectAttrsObj[attr.id]);
              return;
            }
            attrArray.push({
              id: attr.id,
              options: "",
              visible: attr.visible,
            });
          });
          dataForm.baseAttrs.push(attrArray);
        });
      }
    });
};

// 表单数据提交
const dataFormSubmit = () => {
  if (submitted.value) {
    return;
  }
  // 转换最终提交数据格式
  let baseAttrs = [];
  dataForm.baseAttrs.forEach((item) => {
    item.forEach((attr) => {
      let { id, options, visible } = attr;
      // 跳过没有录入值的属性
      if (options instanceof Array && options.length > 0) {
        options = options.join(";");
        baseAttrs.push({ id, options, visible });
      } else if (typeof options === "string" && options) {
        baseAttrs.push({ id, options, visible });
      }
    });
  });
  // 规则参数不能为空
  if (baseAttrs.length <= 0) {
    ElMessage.warning("请先设置规格参数，再进行保存操作！");
    return;
  }
  submitted.value = true;
  http
    .instance({
      url: http.adornUrl(`/product/spu/saveBaseAttrs?spuId=${dataForm.id}`),
      data: http.adornData(baseAttrs, false),
    })
    .then(({ data }) => {
      if (http.success(data, true, true)) {
        visible.value = false;
        emit("loadTableData");
      }
      submitted.value = false;
    });
};

// 暴露方法
defineExpose({ initForm });
</script>
